package com.zhijian.medical.service.impl;

import cn.hutool.core.date.DateUtil;
import com.zhijian.medical.entity.UploadParam;
import com.zhijian.medical.entity.vo.response.UploadVo;
import com.zhijian.medical.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author HCG
 * @version 1.0
 * @date 2022/1/3
 */
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private UploadParam uploadParam;

    @Override
    public UploadVo upload(MultipartFile file) {
        String today = DateUtil.format(new Date(), new SimpleDateFormat("yyyy/MM/dd"));
        String fileName = file.getOriginalFilename();
        String filePath = String.format("%s%s%s%s%s", uploadParam.getStorePath(), File.separator, today, File.separator, fileName);
        File dest = new File(filePath);

        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);

            return UploadVo.builder()
                    .realPath(filePath)
                    .fileName(fileName)
                    .urlPath(String.format("%s%s%s%s", uploadParam.getUrlPath(), today, File.separator, fileName))
                    .build();
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public UploadVo uploadDsc(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String filePath = String.format("%s%s", uploadParam.getDscPath(), fileName);
        File dest = new File(filePath);

        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);

            return UploadVo.builder()
                    .realPath(filePath)
                    .fileName(fileName)
                    .urlPath(String.format("%s%s%s", "http://36.139.55.74:5000/file", File.separator, fileName))
                    .build();
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
